package test;

import java.util.Stack;

/*
       题目:
       150. 逆波兰表达式求值
       数据
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: 该算式转化为常见的中缀算术表达式为：((2 + 1) * 3) = 9
示例 2：

输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: 该算式转化为常见的中缀算术表达式为：(4 + (13 / 5)) = 6

使用栈来实现
 */
public class letcode150_nibolanqiuzhi {
    private boolean isOperator(String token){
        return "+-*/".contains(token);
    }
    private int calculate(Integer left,Integer right,String operator){
    switch (operator){
        case "+":return left+right;
        case "-":return left-right;
        case "*":return left*right;
        default:return left/right;
      }
    }
    public int evalRPN(String[] tokens){
        Stack<Integer> stack=new Stack<Integer>();
     for(String token:tokens){
         if(isOperator(token)){
             Integer right=stack.pop();
             Integer left=stack.pop();
    stack.push(calculate(left,right,token));
         }else{
          stack.push(Integer.parseInt(token));
         }
     }
     return stack.pop();
    }
}
